// Copyright 2007 the original author or authors.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//     http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

package lichen.pages.topic;

import java.util.List;

import lichen.entities.post.Comment;
import lichen.entities.post.Post;
import lichen.entities.post.Topic;
import lichen.pages.base.BasePage;
import lichen.pages.base.LogInfoPage;
import lichen.pages.base.MenuPage;
import lichen.services.menu.Menu;
import lichen.services.menu.impl.MenuImpl;
import lichen.services.post.PostService;

import org.apache.tapestry.annotations.Inject;
import org.apache.tapestry.annotations.InjectPage;

/**
 * 对主题进行注释
 * @author <a href="mailto:jun.tsai@gmail.com">Jun Tsai</a>
 * @version $Revision: 7 $
 * @since 0.0.1
 */
public class CommentTopic extends BasePage  implements LogInfoPage,MenuPage{
	/** 当前操作的注释类 **/
	private Comment comment;
	@Inject
	/** Post Service **/
	private PostService postService;

	/**  返回的页面类 **/
	@InjectPage
	private ViewTopic viewTopic;

	/** 当前操作对应的主题 **/
	private Topic topic;
	/** 父实体对象  **/
	private Post parentPost;

	/**
	 * 页面激活的时候.
	 * @param parentPost 父贴子.
	 */
	void onActivate(Post parentPost) {
		if(parentPost.isTopic()){
			//重新加载，好让当前的post对应的能够load为Topic对象
			this.topic = (Topic) this.getHibernateSession().load(Topic.class,parentPost.getId());
		}else{
			this.topic=parentPost.getParentTopic();
		}
		this.parentPost = parentPost;
		this.comment = new Comment();
	}

	/**
	 * 需要固化的实体对象.
	 * @return 固化的实体对象.
	 */
	Object [] onPassivate() {
		return new Object [] {  this.parentPost };
	}

	/**
	 * 当注释的表单提交的时候.
	 * @return 查看主题的列表页面
	 */
	ViewTopic onActionFromCommentForm() {
		postService.saveComment(this.topic, parentPost, comment);
		viewTopic.setTopic(topic);
		return viewTopic;
	}

	/**
	 * 得到当前的注释类.
	 * @return 当前操作的注释类.
	 */
	public Comment getComment() {
		return this.comment;
	}

	/**
	 * 
	 * @see lichen.pages.base.LogInfoPage#getLogInfo()
	 */
	public String getLogInfo() {
		return getMessages().format("topic.comment",parentPost.getTitle());
	}

	public List<Menu> contributeMenus() {
		List<Menu> menus = this.getMenuService().generateForumMenu(this.topic.getForum(),this.topic);
		StringBuffer action=new StringBuffer();
		action.append(getMessages().format("topic.comment",parentPost.getTitle()));
		menus.add(MenuImpl.newInstance(action.toString()));
		return menus;
	}

}
